﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using OpenComposite.EII.RepositoryUIs;
using OpenComposite.EII.Repository;
using OpenComposite.Base.Collections;

namespace OpenComposite.EII.Forms.OrgDesigner
{
	public partial class DetailsDock : DockContent
	{
		public DetailsDock()
		{
			InitializeComponent();


		}

		#region Public Member
		#region Methods
		public void HideDetails()
		{
			pnlOrgDetails.Visible = false;
			pnlRoleDetails.Visible = false;
			pnlUserDetails.Visible = false;
		}
		public void ShowUserDetails()
		{
			pnlOrgDetails.Visible = false;
			pnlRoleDetails.Visible = false;
			pnlUserDetails.Visible = true;
			if ( UserDetailsShown != null ) {
				UserDetailsShown(this, EventArgs.Empty);
			}
		}

		public void ShowOrgDetails()
		{
			pnlOrgDetails.Visible = true;
			pnlRoleDetails.Visible = false;
			pnlUserDetails.Visible = false;
			if ( OrgDetailsShown != null ) {
				OrgDetailsShown(this, EventArgs.Empty);
			}
		}

		public void ShowRoleDetails()
		{
			pnlOrgDetails.Visible = false;
			pnlRoleDetails.Visible = true;
			pnlUserDetails.Visible = false;
			if ( RoleDetailsShown != null ) {
				RoleDetailsShown(this, EventArgs.Empty);
			}
		}

		public void ShowUserAssignedRolesTab()
		{
			pnlOrgDetails.Visible = false;
			pnlRoleDetails.Visible = false;
			pnlUserDetails.Visible = true;
		}
		public void AddRoleToCurrentUser(ListViewItem item)
		{
			if ( item.Tag is Role ) {
				lvAssignedUserRoles.Items.Add(item.Clone() as ListViewItem);
				_currentUser.AddRole(item.Tag as Role);
			}
		}
		
		public void SaveItemData(IRepositoryItem repositoryItem)
		{
			if ( repositoryItem.RepositoryItemType == ItemType.Organization ) {
				SaveOrganisationData(repositoryItem as Organization);
			} else if ( repositoryItem.RepositoryItemType == ItemType.OrgUnit ) {
				SaveOrgUnitData(repositoryItem as OrganizationalUnit);
			} else if ( repositoryItem.RepositoryItemType == ItemType.Role ) {
				SaveRoleData(repositoryItem as Role);
			} else if ( repositoryItem.RepositoryItemType == ItemType.User ) {
				SaveUserData(repositoryItem as User);
			}
		}

		/// <summary>
		/// Saves the data from the details tab to the specified user.
		/// </summary>
		/// <param name="user">The user to save the user data to.</param>
		public void SaveUserData(User user)
		{
			user.EmployeeId = textBoxEmployeeID.Text;
			user.FirstName = textBoxFirstName.Text;
			user.LastName = textBoxLastName.Text;
			user.MiddleInitials = textBoxMiddleName.Text;
            user.Title = textBoxTitle.Text;
			user.PhonePrivate1 = textBoxPhonePrivate1.Text;
			user.PhonePrivate2 = textBoxPhonePrivate2.Text;
			user.PhoneMobile = textBoxMobile.Text;
			user.Address = textBoxAddress.Text;
			user.City = textBoxCity.Text;
			user.State = textBoxState.Text;
			user.ZipCode = textBoxZIP.Text;
			user.Country = textBoxCountry.Text;
			user.Pager = textBoxPager.Text;
			user.Office = textBoxOffice.Text;
			user.PhoneBusiness1 = textBoxPhoneBusiness1.Text;
			user.PhoneBusiness2 = textBoxPhoneBusiness2.Text;
			user.Fax = textBoxFax.Text;
			// TODO: Phone Assistant
			user.Email = textBoxEmailAddress.Text;
			if ( cmbFirstManager.SelectedItem == null ) {
				user.FirstManagerID = -1;
			} else {
				user.FirstManagerID = (int)cmbFirstManager.SelectedValue;
			}
			if ( cmbSecondManager.SelectedItem == null ) {
				user.SecondManagerID = -1;
			} else {
				user.SecondManagerID = (int)cmbSecondManager.SelectedValue;
			}
			if ( cmbFirstAssistant.SelectedItem == null ) {
				user.FirstAssistantID = -1;
			} else {
				user.FirstAssistantID = (int)cmbFirstAssistant.SelectedValue;
			}
			if ( cmbSecondAssistant.SelectedItem == null ) {
				user.SecondAssistantID = -1;
			} else {
				user.SecondAssistantID = (int)cmbSecondAssistant.SelectedValue;
			}
			user.Notes = textBoxNotes.Text;
			user.UserName = textBoxUserID.Text;
			user.Password = textBoxPassword.Text;
			//user.TimeZone = cmbTimeZone.SelectedValue == null ? -1 : (int)cmbTimeZone.SelectedValue;
			user.LanguageCode = cmbCountrySettings.SelectedValue == null ? -1 : (int)cmbCountrySettings.SelectedValue;
			user.LanguageId = cmbLanguage.SelectedValue == null ? 1 : (int)cmbLanguage.SelectedValue;
			user.DayLightSavings = rbnDLSYes.Checked;
			user.EnableEmailNotifications = rbnEmailNotificationYes.Checked;
			user.IsSystemAdmin = rbnAdminYes.Checked;
			user.IsActiveUser = rbnActive.Checked;
			List<Role> roles = new List<Role>();
			foreach ( ListViewItem item in lvAssignedUserRoles.Items ) {
				Role role = item.Tag as Role;
				if ( role == null ) continue;
				roles.Add(role);
			}
			user.Roles = roles.ToArray();
			user.Save();
		}

		/// <summary>
		/// Displays the data of the specified user in the details tab.
		/// </summary>
		/// <param name="user">The user to display.</param>
		public void DisplayUserData(User user)
		{
			BindingListEx<User> users = Global.Data.GetOrgUsersByOrg(user.OrganizationId);
			users.Insert(0, new User(-1));
			// fill combo boxes
			cmbFirstAssistant.DataSource = new BindingListEx<User>(users);
			cmbFirstManager.DataSource = new BindingListEx<User>(users);
			cmbSecondAssistant.DataSource = new BindingListEx<User>(users);
			cmbSecondManager.DataSource = new BindingListEx<User>(users);
			cmbTimeZone.DataSource = TimeZoneInfo.GetSystemTimeZones();
			cmbLanguage.DataSource = null;
			cmbCountrySettings.DataSource = null;

			_currentUser = user;
			// Personal data
			groupBox1.Text = string.Format("User Details: {0}", user.FormattedName);
			textBoxEmployeeID.Text = user.EmployeeId.ToString();
			textBoxFirstName.Text = user.FirstName;
			textBoxLastName.Text = user.LastName;
			textBoxMiddleName.Text = user.MiddleInitials;
			textBoxTitle.Text = user.Title;
			textBoxPhonePrivate1.Text = user.PhonePrivate1;
			textBoxPhonePrivate2.Text = user.PhonePrivate2;
			textBoxMobile.Text = user.PhoneMobile;
			textBoxAddress.Text = user.Address;
			textBoxCity.Text = user.City;
			textBoxState.Text = user.State;
			textBoxZIP.Text = user.ZipCode;
			textBoxCountry.Text = user.Country;
			textBoxPager.Text = user.Pager;
			// Working place data
			if ( user.Organization != null ) textBoxCompany.Text = user.Organization.Name;
			else textBoxCompany.Text = "";
			if ( user.OrganizationalUnit != null ) textBoxDepartment.Text = user.OrganizationalUnit.Name;
			else textBoxDepartment.Text = "";
			textBoxOffice.Text = user.Office;
			textBoxPhoneBusiness1.Text = user.PhoneBusiness1;
			textBoxPhoneBusiness2.Text = user.PhoneBusiness2;
			textBoxFax.Text = user.Fax;
			textBoxPhoneAssistent.Text = user.PhoneAssistantID;
			textBoxEmailAddress.Text = user.Email;
			if ( user.FirstManager != null ) cmbFirstManager.Text = user.FirstManager.Name;
			else cmbFirstManager.Text = "";
			if ( user.SecondManager != null ) cmbSecondManager.Text = user.SecondManager.Name;
			else cmbSecondManager.Text = "";
			if ( user.FirstAssistant != null ) cmbFirstAssistant.Text = user.FirstAssistant.Name;
			else cmbFirstAssistant.Text = "";
			if ( user.SecondAssistant != null ) cmbSecondAssistant.Text = user.SecondAssistant.Name;
			else cmbSecondAssistant.Text = "";
			textBoxNotes.Text = user.Notes;
			// System data
			textBoxUserID.Text = user.UserName;
			textBoxPassword.Text = user.Password;
			if ( user.LanguageId < 1 ) cmbLanguage.SelectedIndex = 0;
			else cmbLanguage.SelectedValue = user.LanguageId;
			//if ( user.LanguageCode < 1 ) cmbCountrySettings.SelectedIndex = 0;
			//else cmbCountrySettings.SelectedValue = user.LanguageCode;
			if ( user.TimeZone < 1 ) cmbTimeZone.SelectedIndex = 0;
			else cmbTimeZone.SelectedIndex = user.TimeZone;
			rbnDLSNo.Checked = true;
			rbnEmailNotificationNo.Checked = true;
			rbnInactive.Checked = true;
			rbnAdminNo.Checked = true;
			rbnDLSYes.Checked = user.DayLightSavings;
			rbnEmailNotificationYes.Checked = user.EnableEmailNotifications;
			rbnAdminYes.Checked = user.IsSystemAdmin;
			rbnActive.Checked = user.IsActiveUser;
			// Roles
			lvAssignedUserRoles.Items.Clear();
			foreach ( Role role in user.Roles ) {
				ListViewItem item = new ListViewItem();
				item.Text = role.Name;
				item.ImageKey = "role";
				item.Tag = role;
				lvAssignedUserRoles.Items.Add(item);
			}
			textBoxShowOld.Text = user.ShowOldActivities.ToString();
		}

		public void SaveOrganisationData(Organization org)
		{
			org.Name = txtOrgName.Text;
			org.Description = txtOrgDescription.Text;
			org.Save();
		}
		public void DisplayOrganisationData(Organization org)
		{
			_currentOrg = org;
			_currentOrgUnit = null;
			txtOrgName.Text = org.Name;
			txtOrgDescription.Text = org.Description;
		}

		public void SaveOrgUnitData(OrganizationalUnit orgUnit)
		{
			orgUnit.Name = txtOrgName.Text;
			orgUnit.Description = txtOrgDescription.Text;
			orgUnit.Save();
		}
		public void DisplayOrgUnitData(OrganizationalUnit orgUnit)
		{
			_currentOrg = null;
			_currentOrgUnit = orgUnit;
			txtOrgName.Text = orgUnit.Name;
			txtOrgDescription.Text = orgUnit.Description;
		}

		public void SaveRoleData(Role role)
		{
			role.Name = txtRoleName.Text;
			role.Description = txtRoleDescription.Text;
			role.Save();
		}
		public void DisplayRoleData(Role role)
		{
			_currentRole = role;
			txtRoleName.Text = role.Name;
			txtRoleDescription.Text = role.Description;
		}
		#endregion

		#region Properties
		public string RoleName
		{
			get { return txtRoleName.Text; }
			set { txtRoleName.Text = value; }
		}
		public string RoleDescription
		{
			get { return txtRoleDescription.Text; }
			set { txtRoleDescription.Text = value; }
		}

		public string OrganisationName
		{
			get { return txtOrgName.Text; }
			set { txtOrgName.Text = value; }
		}
		public string OrganisationDescription
		{
			get { return txtOrgDescription.Text; }
			set { txtOrgDescription.Text = value; }
		}

		public ListView UserRoles
		{
			get { return lvAssignedUserRoles; }
			set { lvAssignedUserRoles = value; }
		}
		#endregion

		#region Events
		public event EventHandler UpdateRole;
		public event EventHandler UpdateOrg;
		public event EventHandler UpdateUser;
		public event EventHandler UserDetailsShown;
		public event EventHandler OrgDetailsShown;
		public event EventHandler RoleDetailsShown;
		#endregion
		#endregion

		#region Private Member
		#region Fields
		private User _currentUser = null;
		private Organization _currentOrg = null;
		private OrganizationalUnit _currentOrgUnit = null;
		private Role _currentRole = null;
		#endregion

		#region Event Handler
		#region Update Role Details
		private void txtRoleName_KeyUp(object sender, KeyEventArgs e)
		{
			if ( e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return ) {
				updateRole();
			}
		}

		private void txtRoleName_Leave(object sender, EventArgs e)
		{
			updateRole();
		}

		private void txtRoleDescription_KeyUp(object sender, KeyEventArgs e)
		{
			if ( e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return ) {
				updateRole();
			}
		}

		private void txtRoleDescription_Leave(object sender, EventArgs e)
		{
			updateRole();
		}
		#endregion

		#region Update Organisation Details
		private void txtOrgName_KeyUp(object sender, KeyEventArgs e)
		{
			if ( e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return ) {
				updateOrg();
			}
		}

		private void txtOrgName_Leave(object sender, EventArgs e)
		{
			updateOrg();
		}

		private void txtOrgDescription_KeyUp(object sender, KeyEventArgs e)
		{
			if ( e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return ) {
				updateOrg();
			}
		}

		private void txtOrgDescription_Leave(object sender, EventArgs e)
		{
			updateOrg();
		}
		#endregion

		#region Update User Details

		#endregion
		#endregion

		#region Methods
		private void updateRole()
		{
			if ( UpdateRole != null ) {
				UpdateRole(this, EventArgs.Empty);
			}
		}

		private void updateOrg()
		{
			if ( UpdateOrg != null ) {
				UpdateOrg(this, EventArgs.Empty);
			}
		}

		private void updateUser()
		{
			if ( UpdateUser != null ) {
				UpdateUser(this, EventArgs.Empty);
			}
		}
		#endregion

		private void tabUserDetails_Leave(object sender, EventArgs e)
		{
			//updateUser();
		}
		#endregion

		private void DetailsDock_Leave(object sender, EventArgs e)
		{
			if ( !textBoxUserID.Focused ) {
				textBoxUserID.Focus();
			}
			if ( pnlUserDetails.Visible == true ) {
				updateUser();
			}
		}

		protected override void OnResize(EventArgs e)
		{
			base.OnResize(e);
			this.Refresh();
		}

		private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
		{
			this.Refresh();
		}

		private void DetailsDock_Shown(object sender, EventArgs e)
		{
			panel5.Width = tabUserDetails.Width - panel5.Left - 10;
		}
	}
}
